<template>
  <div>
    <el-card>
      <!-- 搜索 添加 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入学生姓名"
                    v-model="queryInfo.name"
                    clearable
                    @clear="getStudentList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getStudentList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary"
                     @click="addDialogVisible = true">添加学生</el-button>
        </el-col>
      </el-row>
      <el-table :data="list"
                border
                stripe>
        <el-table-column prop="id"
                         label="ID"
                         width="100"></el-table-column>
        <el-table-column prop="name"
                         label="姓名"> </el-table-column>
        <el-table-column prop="age"
                         label="年龄"> </el-table-column>
        <el-table-column prop="sex"
                         label="性别"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       circle
                       @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       circle
                       @click="removeById(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <!-- 添加学生的对话框 -->
    <el-dialog title="添加学生"
               :visible.sync="addDialogVisible"
               width="30%"
               center
               @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="addForm"
               ref="addFormRef"
               :rules="addFormRules"
               label-width="100px">
        <el-form-item label="姓名"
                      prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄"
                      prop="age">
          <el-input v-model.number="addForm.age"></el-input>
        </el-form-item>

        <el-form-item label="性别"
                      prop="sex">
          <el-radio v-model="addForm.sex"
                    label="女">女</el-radio>
          <el-radio v-model="addForm.sex"
                    label="男">男</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer"
            width="30%"
            center>
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="add">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改学生的对话框 -->
    <el-dialog title="修改学生信息"
               :visible.sync="editDialogVisible"
               width="30%"
               center
               @close="editDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="editForm"
               ref="editFormRef"
               :rules="editFormRules"
               label-width="70px">
        <el-form-item label="姓名">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model.number="editForm.age"></el-input>
        </el-form-item>

        <el-form-item label="性别"
                      prop="sex">
          <el-radio v-model="editForm.sex"
                    label="女">女</el-radio>
          <el-radio v-model="editForm.sex"
                    label="男">男</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="edit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { studentList } from "../data/data";
import Vue from "vue";

export default {
  name: "Student",
  data() {
    return {
      // 初始id，以后累加即可
      startId: 100,
      olist: JSON.parse(JSON.stringify(studentList)),
      list: JSON.parse(JSON.stringify(studentList)),
      // 选中的学生
      selectedStudent: {},
      selectedIndex: null,
      // 获取学生列表查询参数对象
      queryInfo: {
        name: "",
      },
      // 添加学生对话框
      addDialogVisible: false,
      // 学生添加
      addForm: {
        id: "",
        name: "",
        age: "",
        sex: "女",
      },

      // 学生添加表单验证规则
      addFormRules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "姓名的长度在2～10个字",
            trigger: "blur",
          },
        ],
        age: [
          { required: true, message: "请输入年龄" },
          { type: "number", message: "年龄必须为数字值" },
        ],
      },

      // 修改学生
      editDialogVisible: false,
      editForm: {},
      // 编辑学生表单验证
      editFormRules: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        age: [
          { required: true, message: "请输入年龄", trigger: "blur" },
          { type: "number", message: "数量必须为数字值" },
        ],
      },
    };
  },
  methods: {
    // 监听 添加学生对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 监听修改学生对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    getStudentList() {
      // 模糊查询
      if (this.queryInfo.name != "") {
        this.list = this.olist.filter((p) => {
          return p.name.indexOf(this.queryInfo.name) > -1;
        });
      } else {
        this.list = this.olist;
      }
    },
    // 修改学生信息
    add() {
      // 提交请求前，表单预验证
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return;
        let e = {
          id: this.startId++,
          name: this.addForm.name,
          age: this.addForm.age,
          sex: this.addForm.sex,
        };
        this.olist.push(e);
        // 隐藏添加学生对话框
        this.addDialogVisible = false;
        this.$message.success("添加成功！");
        this.getStudentList();
      });
    },
    handleEdit(row) {
      this.editDialogVisible = true;
      this.editForm = Object.assign({}, row);
      this.selectedIndex = this.getIndexById(row.id);
      // console.log(row)
    },
    // 提交修改
    edit() {
      // 提交请求前，表单预验证
      this.$refs.editFormRef.validate(async (valid) => {
        // 表单预校验失败
        if (!valid) return;
        // 查找对象
        var s = this.olist[this.selectedIndex];
        console.log(JSON.stringify(s));
        s.name = this.editForm.name;
        s.age = this.editForm.age;
        s.sex = this.editForm.sex;

        Vue.set(this.olist, this.selectedIndex, s);

        // 隐藏添加学生对话框
        this.editDialogVisible = false;
        this.$message.success("修改成功！");
        this.getStudentList();
      });
    },
    // 删除学生
    removeById(id) {
      this.olist.splice(this.getIndexById(id), 1);
      this.$message.success("删除成功！");
      this.getStudentList();
    },
    // 根据学生ID获取学生对象
    getIndexById(id) {
      var s = this.olist.filter((p) => {
        return p.id == id;
      });

      if (s != null) {
        return this.olist.indexOf(s[0]);
      } else {
        alert("未找到数据！");
        return -1;
      }
    },
  },
};
</script>
